package gcosc.fun.hly.fastsso.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gcosc.fun.hly.fastsso.domain.Bo.PageQuery;
import gcosc.fun.hly.fastsso.domain.SsoUser;
import gcosc.fun.hly.fastsso.mapper.SsoUserMapper;
import gcosc.fun.hly.fastsso.result.Code;
import gcosc.fun.hly.fastsso.result.TableDataInfo;
import gcosc.fun.hly.fastsso.service.ISsoRoleService;
import gcosc.fun.hly.fastsso.service.SsoUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SsoUserServiceImpl extends ServiceImpl<SsoUserMapper, SsoUser> implements SsoUserService {

    private final ISsoRoleService iSsoRoleService;


    /**
     * 查询用户
     */
    @Override
    public SsoUser queryById(Long id){
        SsoUser ssoUser = baseMapper.selectById(id);

        ssoUser.setRoles(iSsoRoleService
                .listRoleByUserId(ssoUser.getId(),
                        ssoUser.getRealm()));

        return ssoUser;
    }

    /**
     * 查询用户列表
     */
    @Override
    public TableDataInfo<SsoUser> queryPageList(SsoUser bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SsoUser> lqw = buildQueryWrapper(bo);
        IPage<SsoUser> result = baseMapper.selectPage(pageQuery.<SsoUser>build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户列表
     */
    @Override
    public List<SsoUser> queryList(SsoUser bo) {
        LambdaQueryWrapper<SsoUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<SsoUser> buildQueryWrapper(SsoUser bo) {
        LambdaQueryWrapper<SsoUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), SsoUser::getUsername, bo.getUsername());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), SsoUser::getEmail, bo.getEmail());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SsoUser::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), SsoUser::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), SsoUser::getSex, bo.getSex());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), SsoUser::getRealName, bo.getRealName());
        lqw.eq(StringUtils.isNotBlank(bo.getRealm()), SsoUser::getRealm, bo.getRealm());
        return lqw;
    }

    /**
     * 新增用户
     */
    @Override
    public Boolean insertByBo(SsoUser bo) {
        SsoUser add = BeanUtil.toBean(bo, SsoUser.class);
        validEntityBeforeSave(add);

        bo.setPassword(SecureUtil.md5(bo.getPassword()));

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            iSsoRoleService.editRoleUser(add.getId(), add.getRealm(), bo.getRoles());
        }
        return flag;
    }

    /**
     * 修改用户
     */
    @Override
    public Boolean updateByBo(SsoUser bo) {
        SsoUser update = BeanUtil.toBean(bo, SsoUser.class);
        validEntityBeforeSave(update);
        iSsoRoleService.editRoleUser(update.getId(), update.getRealm(), bo.getRoles());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SsoUser entity){
        //TODO 做一些数据校验,如唯一约束

        if (entity.getRealm() == null ||
                entity.getUsername() == null){
            Code.BUSINESS_ERR("参数有误");
        }

        SsoUser ssoUser = getUserByRealmAndUserName(entity.getRealm(),
                entity.getUsername());

        if (ssoUser != null && entity.getId() == null ||
            entity.getId() != null && !ssoUser.getId().equals(entity.getId())){
            Code.BUSINESS_ERR("用户名已经存在");
        }
    }

    /**
     * 批量删除用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public SsoUser getUserByRealmAndUserName(String realm, String username) {
        return getOne(Wrappers.
                <SsoUser>lambdaQuery()
                .select(SsoUser::getPassword,
                        SsoUser::getId,
                        SsoUser::getAge,
                        SsoUser::getRealm,
                        SsoUser::getRealName,
                        SsoUser::getEmail,
                        SsoUser::getPhone,
                        SsoUser::getUsername)
                .eq(SsoUser::getRealm, realm)
                .eq(SsoUser::getUsername, username));
    }

}
